package com.manlitech.manlichat.util.websocketclient;


import com.google.protobuf.util.JsonFormat;
import com.manlitech.manlichat.proto.GameMsgProtocol;
import com.manlitech.manlichat.proto.ProtoMsg;
import com.manlitech.manlichat.util.SslUtil;
import org.java_websocket.WebSocket;
import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;


import javax.net.ssl.*;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author Shensg
 * socket 客户端
 */
public class MyWebSocketClient extends WebSocketClient {

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
        if(serverUri.toString().contains("wss://")){
            trustAllHosts(this);
        }

    }

    public MyWebSocketClient(URI serverURI, Draft draft) {
        super(serverURI,draft);
        if(serverURI.toString().contains("wss://")) {
            trustAllHosts(this);
        }
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };


    static void trustAllHosts(MyWebSocketClient appClient) {
        System.out.println("wss");
        SslUtil.trustAllCerts();

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, SslUtil.trustAllCerts(), new java.security.SecureRandom());
            appClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    @Override
    public void onOpen(ServerHandshake arg0) {
        System.out.println("握手成功");

    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("连接关闭");
    }

    @Override
    public void onError(Exception arg0) {
        arg0.printStackTrace();
        System.out.println("发生错误");
    }

    @Override
    public void onMessage(String arg0) {
        System.out.println("接受到服务端文本text消息:" + arg0);
    }

    @Override
    public void onMessage(ByteBuffer buffer) {
        CharBuffer charBuffer = null;
        try {
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();
            charBuffer = decoder.decode(buffer);
            buffer.flip();
            System.out.println("接受到服务端二进制binary消息: " + charBuffer.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    public static void main(String[] args){

        String url = "wss://localhost:8098/ws";
        try {

            MyWebSocketClient myClient = new MyWebSocketClient(new URI(url));
            myClient.connect();
            // 判断是否连接成功，未成功后面发送消息时会报错
            while (!myClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println("连接中···请稍后");
                Thread.sleep(1000);
            }
            //二进制
            //myClient.send(MyWebSocketClient.byteMerger("12ABCDabcdfe".getBytes(StandardCharsets.UTF_8) , "中国".getBytes(StandardCharsets.UTF_8)));
            //text文本
            //myClient.send("MyClient");
            //二进制 proto
            //GameMsgProtocol.UserEntryCmd userEntryCmd = GameMsgProtocol.UserEntryCmd.newBuilder().setUserId(1).setHeroAvatar("ssg大哥").build();
            //myClient.send(ByteUtils.byteMerger("12".getBytes(StandardCharsets.UTF_8), userEntryCmd.toByteArray()));
            //JsonFormat.printer().print(userEntryCmd);
            //com.googlecode.protobuf.format.JsonFormat.merge("", GameMsgProtocol.UserEntryCmd.newBuilder());

            //String httpMsg = SslUtil.httpsGet("https://192.168.1.79:8097/ws?中国");
            //System.out.println("httpsMsg:"+ httpMsg );

            //myClient.send("1231231ssg沈世冠".getBytes());

            ProtoMsg.LoginRequest loginRequest = ProtoMsg.LoginRequest.newBuilder()
                    .setUid("用户id")
                    .setToken("用户token")
                    .build();
            myClient.send(loginRequest.toByteArray());//ByteUtils.byteMerger("69".getBytes(StandardCharsets.UTF_8), loginRequest.toByteArray()));


            System.out.println("发送成功");



        } catch (Exception e) {
            e.printStackTrace();
        }


    }




}
